package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags="菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("{id}")
    @ApiOperation("根据Id查询菜品信息")
    public Result<DishVO> getDishVoById(@PathVariable Long id){
        DishVO dishVO=dishService.getDishById(id);

        return Result.success(dishVO);
    }


    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> getDishById(@RequestParam(required = true)Long categoryId ){
        List<Dish> dish=dishService.getDishByCategoryId(categoryId);
        return Result.success(dish);
    }

    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result<String> saveWithFlavor(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}",dishDTO);
        dishService.saveWithFlavor(dishDTO);

        redisTemplate.delete("*dish_"+dishDTO.getCategoryId());
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("菜品的分页查询")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult =dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售，停售")
    public Result<String> stopOrBegin(@PathVariable int status,@RequestParam(required = true) long id){
        dishService.stopOrBegin(status,id);
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        Set keys = redisTemplate.keys("*dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }
     @PutMapping
    @ApiOperation("修改菜品")
    public Result<String> changeDish(@RequestBody DishDTO dishDTO){
        dishService.updateWithFlavor(dishDTO);
         //将所有的菜品缓存数据清理掉，所有以dish_开头的key
         Set keys = redisTemplate.keys("*dish_*");
         redisTemplate.delete(keys);
        return Result.success();
     }

     @DeleteMapping
     @ApiOperation("批量删除菜品")
     public Result<String> delete(@RequestParam List<Long> ids){
        dishService.deleteBatch(ids);
         //将所有的菜品缓存数据清理掉，所有以dish_开头的key
         Set keys = redisTemplate.keys("*dish_*");
         redisTemplate.delete(keys);
        return Result.success();
     }
}
